package cn.org.wangchangjiu.sqltomongo.core.parser.select_option.impl;

import cn.org.wangchangjiu.sqltomongo.core.adapter.MyOrderByVisitorAdapter;
import cn.org.wangchangjiu.sqltomongo.core.parser.data.GroupData;
import cn.org.wangchangjiu.sqltomongo.core.parser.data.PartSQLParserData;
import cn.org.wangchangjiu.sqltomongo.core.parser.data.SortData;
import cn.org.wangchangjiu.sqltomongo.core.parser.select_option.PlainSelectPartSQLParser;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class OrderSQLParserPlainSelect extends PlainSelectPartSQLParser {

    @Override
    public void proceedData(PlainSelect plain, PartSQLParserData data) {
        List<OrderByElement> orderByElements = plain.getOrderByElements();
        if (!CollectionUtils.isEmpty(orderByElements)) {
            List<String> groupByNames = data.getGroupData().stream().map(GroupData::getField).collect(Collectors.toList());
            List<SortData> sortData = new ArrayList<>();
            orderByElements.stream().forEach(orderByElement -> orderByElement.accept(new MyOrderByVisitorAdapter(sortData)));

            List<SortData> sortData0 = sortData;
            sortData0 = sortData0.stream()
                    .peek(d->{
                        if(groupByNames.contains(d.getOriginExpressionField())){
                            d.setGroupCollectionName("_id");
                        }
                    })
                    .collect(Collectors.toList());
            data.setSortData(sortData0);
        }
    }
}
